/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.chronicles.model;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.libermundi.theorcs.chronicles.ChronicleConstants;
import org.libermundi.theorcs.core.model.base.NumericIdEntity;
import org.libermundi.theorcs.security.model.User;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Entity(name="SavedInformations")
@Table(name=ChronicleConstants.TBL_SAVEDINFOS)
public class SavedInformations extends NumericIdEntity {
	private static final long serialVersionUID = 6312693321076984073L;
	
	public final static String PROP_INFORMATIONS="informations";
	public final static String PROP_USER="user";
	
	private User _user;
	private String _informations;
	private Map<String,String> _infoMap = new HashMap<>();
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="playerId")
	public User getUser() {
		return _user;
	}
	
	public void setUser(User user) {
		_user = user;
	}
	
	@Lob
	@Column(name=SavedInformations.PROP_INFORMATIONS,nullable=false)	
	public String getInformations() {
		return _informations;
	}
	
	public void setInformations(String informations) {
		_informations = informations;
		_infoMap = buildMap();
	}
	
	public String readInformation(String key) {
		return _infoMap.get(key);
	}

	public void addInformation(String key, String value) {
		_infoMap.put(key, value);
		updateInfos();
	}
	
	// ~~ -- Private Methods
	private void updateInfos() {
		Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
		setInformations(buildGson().toJson(_infoMap,typeOfMap));
	}

	@SuppressWarnings("unchecked")
	private Map<String, String> buildMap() {
		return buildGson().fromJson(_informations, HashMap.class);
	}
	
	private static Gson buildGson() {
		return new Gson();
	}
}
